package com.example.esp32_iot;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.hms.hmsscankit.ScanUtil;
import com.huawei.hms.ml.scan.HmsScan;
import com.huawei.hms.ml.scan.HmsScanAnalyzerOptions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private TextView tv;
    private EditText IPet,port;
    private Handler myhandler;
    private Socket socket;
    private String str = "";
    boolean running = false;
    private Button conn,disconn,on,off;
    private StartThread st;
    private ReceiveThread rt;

    public static final int CAMERA_REQ_CODE = 111;
    public static final int DECODE = 1;
    private static final int REQUEST_CODE_SCAN_ONE = 0X01;
    String[] permissions = new String[]{Manifest.permission.READ_PHONE_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = findViewById(R.id.tv);

        IPet = findViewById(R.id.IPet);
        port = findViewById(R.id.port);

        conn = (Button) findViewById(R.id.conn);
        disconn = (Button) findViewById(R.id.disconn);
        on = (Button) findViewById(R.id.on);
        off = findViewById(R.id.off);

        setButtonOnStartState(true);//设置按钮状态为可点击-也就是可以开始连接

        conn.setOnClickListener(this);
        disconn.setOnClickListener(this);
        on.setOnClickListener(this);
        off.setOnClickListener(this);

        myhandler = new MyHandler();

    }

    public void loadScanKitBtnClick(View view) {
        requestPermission(CAMERA_REQ_CODE, DECODE);
    }

    //编辑请求权限
    private void requestPermission(int requestCode, int mode) {
        ActivityCompat.requestPermissions(
                this,
                new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
                requestCode);
    }

    //权限申请返回
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions == null || grantResults == null) {
            return;
        }

        if (grantResults.length < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (requestCode == CAMERA_REQ_CODE) {
            ScanUtil.startScan(this, REQUEST_CODE_SCAN_ONE, new HmsScanAnalyzerOptions.Creator().create());
        }
    }

    //Activity回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (requestCode == REQUEST_CODE_SCAN_ONE) {
            HmsScan obj = data.getParcelableExtra(ScanUtil.RESULT);
            if (obj != null) {
                Toast.makeText(this,obj.originalValue,Toast.LENGTH_SHORT).show();
                IPet.setText(obj.originalValue);
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.conn:
                //此时按下开始连接按键新建线程
                st = new StartThread();
                st.start();
                setButtonOnStartState(false);
                break;
            case R.id.on:
                //发送请求数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OutputStream os = null;
                            os = socket.getOutputStream();//得到socket的输出流
                            //输出EditText里面的数据，数据最后加上换行符才可以让服务器端的readline()停止阻塞
                            os.write(("123\n").getBytes("utf-8"));
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.off:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OutputStream os = null;
                            os = socket.getOutputStream();//得到socket的输出流
                            //输出EditText里面的数据，数据最后加上换行符才可以让服务器端的readline()停止阻塞
                            os.write(("456\n").getBytes("utf-8"));
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
                break;
            case R.id.disconn:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            OutputStream os = null;
                            os = socket.getOutputStream();//得到socket的输出流
                            //输出EditText里面的数据，数据最后加上换行符才可以让服务器端的readline()停止阻塞
                            os.write(("789\n").getBytes("utf-8"));
                        }catch (IOException e){
                            e.printStackTrace();
                        }
                    }
                }).start();
                running = false;
                setButtonOnStartState(true);
                try {
                    socket.close();
                }catch (NullPointerException e){
                    e.printStackTrace();
                    disPlayToast("断开连接");
                }catch (IOException e){
                    e.printStackTrace();
                }
                break;
        }
    }

    private class StartThread extends Thread{
        @Override
        public void run(){
            try {
                int portnum = Integer.parseInt(port.getText().toString());
                socket = new Socket(IPet.getText().toString(),portnum);
                System.out.println(IPet.getText());
                rt = new ReceiveThread(socket);
                rt.start();
                running = true;
                System.out.println(socket.isConnected());
                if(socket.isConnected()){//成功连接，获取socket对象，发送成功消息
                    Message msg0 = myhandler.obtainMessage();
                    msg0.what = 0;
                    myhandler.sendMessage(msg0);
                    tv.setText("已连接ESP32");
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    private class ReceiveThread extends Thread{
        private InputStream is;
        public ReceiveThread(Socket socket) throws IOException{
            is = socket.getInputStream();
        }
        @Override
        public void run(){
            while (running){
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                try {
                    //读取服务器端发过来的数据，阻塞一直到收到结束符\n\r
                    System.out.println(str = br.readLine());
                }catch (NullPointerException e){
                    running = false;
                    Message msg2 = myhandler.obtainMessage();
                    msg2.what = 2;
                    myhandler.sendMessage(msg2);
                    e.printStackTrace();
                    break;
                }catch (IOException e){
                    e.printStackTrace();
                }
                Message msg = myhandler.obtainMessage();
                msg.what = 1;
                msg.obj = str;
                myhandler.sendMessage(msg);
                try{
                    sleep(400);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            Message msg2 = myhandler.obtainMessage();
            msg2.what = 2;
            myhandler.sendMessage(msg2);
        }

    }

    //设置按钮状态
    private void setButtonOnStartState(boolean flag) {
        conn.setEnabled(flag);
        disconn.setEnabled(!flag);
        on.setEnabled(!flag);
        off.setEnabled(!flag);
    }
    private void disPlayToast(String s){
        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
    }

    class MyHandler extends Handler{//在主线程中处理Handler传送回来的额message
        @Override
        public void handleMessage(Message msg){
            switch (msg.what){
                case 1:
                    String str = (String) msg.obj;
                    System.out.println(msg.obj);
                    tv.setText(str);
                    break;
                case 0:
                    disPlayToast("连接成功");
                    break;
                case 2:
                    disPlayToast("服务器已断开");
                    tv.setText(null);
                    setButtonOnStartState(true);
                    break;
            }
        }
    }

}